export default () => {
  /**
   *
   * @param {string} key
   * @param {any} data
   * @param {number} expire
   */
  function set(key, data, expire) {
    let cache = { data, expire }
    if (expire) {
      cache.expire = new Date().getTime() + expire * 1000
    }
    localStorage.setItem(key, JSON.stringify(cache))
  }

  /**
   *
   * @param {string} key
   * @param {null} defaultValue
   * @returns {any}
   */
  function get(key, defaultValue = null) {
    const cacheStore = localStorage.getItem(key)
    if (cacheStore) {
      const cache = JSON.parse(cacheStore)
      const expire = cache?.expire
      if (expire && expire < new Date().getTime()) {
        localStorage.removeItem(key)
        return defaultValue
      }
      return cache.data
    }
    return defaultValue
  }

  /**
   *
   * @param {string} key
   */
  function remove(key) {
    localStorage.removeItem(key)
  }
  function clear() {
    localStorage.clear()
  }

  return { set, get, remove, clear }
}
